<template>
  <div id="LiveResourcePage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">直播筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">区域</span>
          <el-select
            class="item-input"
            v-model="queryObj.areaName"
            placeholder="选择区域"
            clearable
            filterable
            @change="areaChangeHandle"
          >
            <el-option
              v-for="item in globalData.areaList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">频道名</span>
          <el-select
            class="item-input"
            v-model="queryObj.channelName"
            placeholder="输入频道名"
            clearable
            filterable
            @change="channelChangeHandle"
          >
            <el-option
              v-for="item in globalData.channelList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
        <div v-if="isShowAddBtn" class="add-btn" @click="addHandle">添加</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">资源详情</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="areaName" label="区域" min-width="130" />
          <el-table-column prop="channelName" label="频道" min-width="150" />
          <el-table-column v-if="false" label="预览地址" min-width="300">
            <template #default="scope">
              <div>{{ scope.row.previewUrl }}</div>
            </template>
          </el-table-column>
          <el-table-column label="信号状态" min-width="150">
            <template #default="scope">
              <div
                class="signal-status"
                :class="scope.row.signalStatus === 0 ? 'normal' : 'abnormal'"
              >
                {{ scope.row.signalStatus === 0 ? "正常" : "异常" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <div
                class="table-btn"
                @click="previewHandle(scope.row.previewUrl)"
              >
                查看
              </div>
              <div
                v-if="isShowAddBtn"
                class="table-btn"
                @click="editHandle(scope.row)"
              >
                编辑
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.currentPage"
        :total="pagination.totalCount"
        :page-size="pagination.numPerPage"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
    <!-- 预览弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="previewDialogVisible"
      title="频道详情"
      width="70%"
    >
      <div class="preview-wrapper">
        <div class="preview-player">
          <!-- <XGPlayer :url="previewUrl" /> -->
          <ckplayer
            :data="{
              url: previewUrl,
              name: '直播预览',
              isLive: true,
              flashplayer: false,
              autoplay: true,
              videoUrl: previewUrl,
            }"
          ></ckplayer>
        </div>
      </div>
    </el-dialog>

    <!-- 添加资源弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="添加直播资源"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="区域" prop="areaName">
          <el-select
            v-model="addForm.areaName"
            placeholder="选择区域"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in globalData.areaList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="频道" prop="channelName">
          <el-select
            v-model="addForm.channelName"
            filterable
            placeholder="选择频道"
            style="width: 100%"
          >
            <el-option
              v-for="item in globalData.channelList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="信号状态" prop="signalStatus">
          <el-select
            v-model="addForm.signalStatus"
            placeholder="选择信号状态"
            style="width: 100%"
          >
            <el-option label="正常" :value="0" />
            <el-option label="异常" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="预览地址" prop="previewUrl">
          <el-input
            v-model="addForm.previewUrl"
            placeholder="输入预览地址"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { ListResponseType, PaginationType } from "@/api/globalType";
import {
  getLiveResourceListAPI,
  addOrUpdateLiveResourceAPI,
  GetLiveResourceListQueryType,
  LiveResourceType,
  AddOrUpdateLiveResourceQueryType,
} from "@/api/service/liveResource";
// import XGPlayer from "@/components/Player/xgplayer.vue";
import ckplayer from "@/components/Player/ckplayer.vue";
import { useRoute } from "vue-router";

const route = useRoute();
const addBtn = route.query.addBtn as string;
const isShowAddBtn = ref(true);
if (addBtn === "true") {
  isShowAddBtn.value = true;
}

const instance = getCurrentInstance();
// 访问全局数据
const globalData = instance?.appContext.config.globalProperties.$globalData;

// 查询条件
const queryObj = ref<GetLiveResourceListQueryType>({
  areaName: "",
  channelName: "",
});

// 分页
const pagination = ref<PaginationType>({
  currentPage: 1,
  numPerPage: 50,
  totalCount: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<LiveResourceType[]>([]);

// API调用保护状态
const listApiLoading = ref(false);

function getLiveResourceList() {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  getLiveResourceListAPI({
    areaName: queryObj.value.areaName,
    channelName: queryObj.value.channelName,
    currentPage: pagination.value.currentPage,
    numPerPage: pagination.value.numPerPage,
  })
    .then((_data: any) => {
      const data = _data as ListResponseType<LiveResourceType>;
      tableData.value = data.list;
      pagination.value.currentPage = data.currentPage;
      pagination.value.numPerPage = data.numPerPage;
      pagination.value.totalCount = data.totalCount;
      pagination.value.totalPages = data.totalPages;
    })
    .catch(() => {
      ElMessage.error("获取直播资源列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getLiveResourceList();

// 区域变化
function areaChangeHandle(areaName: string) {
  pagination.value.currentPage = 1;
  queryObj.value.areaName = areaName;
  getLiveResourceList();
}

// 频道变化
function channelChangeHandle(channelName: string) {
  pagination.value.currentPage = 1;
  queryObj.value.channelName = channelName;
  getLiveResourceList();
}

// 筛选
function searchHandle() {
  pagination.value.currentPage = 1;
  getLiveResourceList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.numPerPage = size;
  pagination.value.currentPage = 1;
  getLiveResourceList();
}
// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.currentPage = currentPage;
  getLiveResourceList();
}

// 预览视频
const previewDialogVisible = ref(false);
const previewUrl = ref<string>("");
function previewHandle(url: string) {
  previewDialogVisible.value = true;
  if (!url) {
    url = globalData.defaultChannelPreviewUrl;
  }
  previewUrl.value = url;
}

// 添加资源
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);

function addHandle() {
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑资源
function editHandle(row: LiveResourceType) {
  addDialogVisible.value = true;
  addForm.value = {
    id: row.id,
    areaName: row.areaName,
    channelName: row.channelName,
    signalStatus: row.signalStatus,
    previewUrl: row.previewUrl,
  };
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}
// 添加表单数据
const addForm = ref<AddOrUpdateLiveResourceQueryType>({
  id: "",
  areaName: "",
  channelName: "",
  signalStatus: 0,
  previewUrl: "",
});

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  areaName: [{ required: true, message: "选择区域", trigger: "blur" }],
  channelName: [{ required: true, message: "选择频道", trigger: "blur" }],
  signalStatus: [{ required: true, message: "选择信号状态", trigger: "blur" }],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    areaName: "",
    channelName: "",
    signalStatus: 0,
    previewUrl: "",
  };
  addFormRef.value?.clearValidate();
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;
      addOrUpdateLiveResourceAPI({
        id: addForm.value.id,
        areaName: addForm.value.areaName,
        channelName: addForm.value.channelName,
        signalStatus: addForm.value.signalStatus,
        previewUrl: addForm.value.previewUrl,
      })
        .then(() => {
          ElMessage.success(
            addForm.value.id ? "编辑直播资源成功" : "添加直播资源成功"
          );
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          pagination.value.currentPage = 1;
          getLiveResourceList();
        })
        .catch(() => {
          ElMessage.error(
            addForm.value.id ? "编辑直播资源失败" : "添加直播资源失败"
          );
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}
</script>

<style scoped lang="scss">
#LiveResourcePage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 2rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 3px;
  height: 1.8rem;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  background-color: #fff;
  flex-shrink: 0;
  padding: 1.5rem 0;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    padding: 2rem 2rem 0 2rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    .item-label {
      display: inline;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: right;
      color: $text-color-regular;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    display: flex;
    align-items: center;
    height: 3rem;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn {
    position: absolute;
    right: 5.8rem;
    top: 2rem;
    display: flex;
    align-items: center;
    height: 3rem;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem 0;
  background-color: #fff;
  .table-wrapper {
    padding: 0 2rem;
    flex: 1;
    min-height: 0;
    margin-top: 1.5rem;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .signal-status.normal {
    color: $color_success;
  }
  .signal-status.abnormal {
    color: $color_danger;
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}

// 设置宽高16:9
:deep(.el-dialog) {
  margin-top: 3rem !important;
}
.preview-wrapper {
  width: 100%;
  padding-top: 56.25%;
  position: relative;
  .preview-player {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }
}

// 添加资源弹框样式
:deep(.el-form-item__label) {
  color: $text-color-regular;
  font-weight: normal;
}

:deep(.el-input__wrapper) {
  border-radius: 0.5rem;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 0.5rem;
}

:deep(.el-button--primary) {
  background-color: $color_brand;
  border-color: $color_brand;
  border-radius: 0.5rem;
}

:deep(.el-button) {
  border-radius: 0.5rem;
}

.dialog-footer {
  text-align: right;
}
</style>
